import random
from st2reactor.sensor.base import PollingSensor

class st2testsensor(PollingSensor):
    """
    st2test sensor
    """
    def __init__(self, sensor_service, config=None, poll_interval=None):
        """
        初始化
        """
        super(st2testsensor, self).__init__(sensor_service=sensor_service, config=config, poll_interval=poll_interval)
        self._logger = self._sensor_service.get_logger(__name__)
        
    def setup(self):
        """
        启动时执行一次
        """
        pass

    def poll(self):
        """
        定时执行，这里需要dispatch trigger，dispatch的方法是父类内置的直接self调用即可
        """
        sourceinfo = random.randint(1,100)  # 这里只是生成了一个随机数，相当于模拟获取数据源
        number = sourceinfo % 2 + 1  # 这里会对3进行取余数，为了后续3个action做对应匹配执行，相当于模拟获取到数据源后的第一次处理
        if number == 1:
            msg = "action1"

        elif number == 2:
            msg = "action2"

        elif number == 3:
            msg = "action3"
        else:
            self.number = "ERROR"

        payload = {"number": str(number), "msg": msg}
        self._sensor_service.dispatch(trigger='st2test.st2testtrigger', payload=payload)

    
    # 以下内容皆可忽略
    def cleanup(self):
        pass

    def add_trigger(self, trigger):
        pass

    def update_trigger(self, trigger):
        pass

    def remove_trigger(self, trigger):
        pass
